<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class UserStatistic extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'user_statistics';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'user_id', 'total_training_sessions', 'successful_sessions',
        'consecutive_days', 'last_training_date', 'total_experience_points'
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'last_training_date' => 'date',
    ];

    /**
     * 所属用户关系
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * 计算成功率
     */
    public function getSuccessRateAttribute()
    {
        if ($this->total_training_sessions == 0) {
            return 0;
        }
        
        return round(($this->successful_sessions / $this->total_training_sessions) * 100, 1);
    }

    /**
     * 增加训练会话统计
     */
    public function incrementTrainingSession($isSuccessful = false)
    {
        $this->increment('total_training_sessions');
        
        if ($isSuccessful) {
            $this->increment('successful_sessions');
        }

        // 更新连续训练天数
        $this->updateConsecutiveDays();
    }

    /**
     * 增加经验值
     */
    public function addExperiencePoints($points)
    {
        $this->increment('total_experience_points', $points);
    }

    /**
     * 更新连续训练天数
     */
    private function updateConsecutiveDays()
    {
        $today = now()->toDateString();
        $yesterday = now()->subDay()->toDateString();

        if ($this->last_training_date == $yesterday) {
            // 连续训练
            $this->increment('consecutive_days');
        } elseif ($this->last_training_date != $today) {
            // 重新开始计算
            $this->consecutive_days = 1;
        }

        $this->last_training_date = $today;
        $this->save();
    }
}